------------------------------------------------------------------------------------------------------------------------
-- This script grabs semantic conventions from the opentelemetry specification repository and generates Lua modules
-- for each file.
------------------------------------------------------------------------------------------------------------------------

local pl_dir = require('pl.dir')
local pl_file = require('pl.file')
local files_by_dir = {}
local dirs = pl_dir.getdirectories("tmp/opentelemetry-specification/semantic_conventions/trace/")

for _i, dir in ipairs(dirs) do
    print(dir)
    table.insert(files_by_dir, pl_dir.getfiles(dir, "*.yaml"))
end

table.insert(
    files_by_dir, pl_dir.getfiles("tmp/opentelemetry-specification/semantic_conventions/trace/", "*.yaml")
)

local lyaml = require("lyaml")

for _i, dir in ipairs(files_by_dir) do
    for _i, file in ipairs(dir) do
        print(file)
        local filename = string.match(file, "tmp/opentelemetry%-specification/semantic_conventions/trace/(%a+)")
        local outfile = "lib/opentelemetry/semantic_conventions/trace/" .. filename .. ".lua"
        local f = io.open(file, "rb")
        local content = f:read("*all")
        f:close()
        local data = lyaml.load(content)
        print("Writing semantic conventions to " .. outfile)
        local out_str = "--- This file was automatically generated by utils/generate_semantic_conventions.lua\n"
        out_str = out_str .. "-- See: https://github.com/open-telemetry/opentelemetry-specification/tree/main/specification/trace/semantic_conventions\n"
        out_str = out_str .. "--\n"
        out_str = out_str .. "-- module @semantic_conventions.trace." .. filename .. "\n\n"
        out_str = out_str .. "local _M = {"

        local attr_string = ""
        for _i, group in ipairs(data.groups) do
            local prefix = group.prefix or ""
            local prop_prefix = string.upper(string.gsub(prefix, "%.", "_"))
            if group.attributes then
                for _i, attr in ipairs(group.attributes) do
                    if attr.id then
                        local brief = string.gsub((attr.brief or attr.id), "\n", "")
                        local attr_id_prop = string.upper(string.gsub(attr.id, "%.", "_"))
                        local attr_id = attr.id
                        if prefix then
                            attr_id_prop = prop_prefix .. "_" .. attr_id_prop
                            attr_id = prefix .. "." .. attr_id
                        end
                        local new_attr = "\n-- " .. brief .. "\n" .. attr_id_prop .. " = " .. "\"" .. attr_id .. "\","
                        attr_string = attr_string .. new_attr
                    end
                end
            end
        end
        pl_file.write(outfile, out_str .. attr_string .. "\n}\n return _M")
    end
end

print("Finished writing semantic conventions. Run `git diff` to see any changes.")
